<template>
  <div>
    <div class="question-content">
      <div class="left">
        <div class="car-model-list">
          <div
            v-for="(group, index) in carList"
            :key="index"
            :class="['car-model-item', { active: activeCarId === group.carId }]"
            @click="tabHandle(group)"
          >
            <div class="name">
              <img src="@/assets/img/question.png" class="material-icon" />
              <span>{{ group.carName }}</span>
            </div>
            <div class="count">{{ group.questionCount }}</div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="header">
          <h3>{{ activeCarName }}</h3
          ><p v-if="staticsQuestionDataInfo">{{ staticsQuestionDataInfo }}</p>
        </div>

        <el-form :model="form" label-width="auto" @keydown.enter.prevent="getData">
          <el-row :gutter="48">
            <el-col :span="6">
              <el-form-item label="课程标题">
                <el-input v-model="form.questionName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="课程类型">
                <el-select
                  v-model="form.questionType"
                  clearable
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="操作时间">
                <el-date-picker
                  label="操作时间："
                  v-model="timeRange"
                  type="datetimerange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  date-format="YYYY/MM/DD ddd"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  time-format="A hh:mm:ss"
                  @change="getTime"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="12">
          <el-button style="margin-right: 10px" @click="handleAdd" type="primary"
            >新增课程</el-button
          >
          <el-button type="danger" :disabled="!selectIds.length" @click="batchDel"
            >批量删除</el-button
          >
        </el-row>
        <art-table
          :data="tableData"
          v-loading="tableLoading"
          :currentPage="pageNum"
          :pageSize="pageSize"
          :total="pageTotal"
          @current-change="currentchange"
          @size-change="sizechange"
          @selection-change="handleSelectionChange"
        >
          <template #default>
            <el-table-column type="selection" width="55" />
            <el-table-column label="ID" prop="id" width="100" />
            <!-- 视频内容 -->
            <el-table-column label="课程标题" prop="bankcont_title" width="500">
              <template #default="scope">
                <div class="title_box">
                  <div class="title_box_right">
                    <div class="bankcont_title">
                      <div class="bankcont_title_text">{{ scope.row.questionName }}</div>
                    </div>
                    <el-button
                      round
                      size="small"
                      plain
                      v-for="(item, index) in scope.row.carModelList"
                      :key="index"
                      >{{ item.carName }}({{ item.carTypes }})</el-button
                    >
                    <!-- 视频类型 -->
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- end视频内容 -->

            <el-table-column label="课程类型">
              <template #default="scope">
                <span>{{
                  typeOptions.find((item) => item.value === scope.row.questionType)?.label
                }}</span>
              </template>
            </el-table-column>

            <!-- 视频链接 -->
            <el-table-column label="视频" prop="videourl">
              <template #default="scope">
                <div @click="handlePreview(scope.row)" style="cursor: pointer">
                  <img :src="scope.row.questionImg" style="width: 100px" />
                </div>
              </template>
            </el-table-column>

            <el-table-column label="视频描述" prop="answer" width="300" />

            <el-table-column #default="scope" label="状态">
              <el-switch
                v-model="scope.row.isDisplay"
                :active-value="1"
                :inactive-value="2"
                @change="handleEditStatus(scope.row.isDisplay, scope.row)"
              />
            </el-table-column>

            <el-table-column label="操作时间" prop="createTime">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
                  <button-table type="edit" @click="buttonMoreClick(scope.row)" />
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
                  <button-table type="delete" @click="deleteRole(scope.row.id)" />
                </el-tooltip>
              </template>
            </el-table-column>
          </template>
        </art-table>
      </div>
    </div>

    <add-object-question-dialog
      v-if="showAddObjectDialog"
      :show-add-object-dialog="showAddObjectDialog"
      :edit-info="editData"
      @close-dialog="handleCloseDialog"
      :category-id="categoryId"
    ></add-object-question-dialog>

    <el-dialog
      v-model="videoDialogVisible"
      width="60%"
      :destroy-on-close="true"
      class="video-dialog"
      :close-on-click-modal="false"
    >
      <template #header>
        <h2>{{ previewTitle }}</h2>
      </template>

      <template #default>
        <video
          v-if="videoDialogVisible"
          :src="previewSrc"
          controls
          autoplay
          style="width: 100%; height: auto"
        />
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import {
    getupdateList,
    delquestionlist,
    putquestioncategory,
    getStatDataToType
  } from '@/api/questionbank'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import addObjectQuestionDialog from './addObjectQuestionDialog.vue'

  const carList = ref<Array<carLists>>([])
  const activeCarId = ref('0')
  const activeCarName = ref('全部')
  const staticsQuestionDataInfo = ref('')

  interface carLists {
    carName: string
    questionCount: string
    carId: string
  }

  const tabHandle = (e: any) => {
    form.carId = e.carId
    activeCarId.value = e.carId
    activeCarName.value = e.carName
    getStatDataToTypeData()
    getData()
  }

  const props = defineProps({
    categoryId: {
      type: String
    },
    carStatc: {
      type: Object
    }
  })

  const emit = defineEmits(['refreshStatc'])

  watch(
    () => props.carStatc,
    (newVal) => {
      carList.value = newVal?.carStatDataList
    },
    { immediate: true, deep: true }
  )

  const tableLoading = ref(false)
  const pageTotal = ref()
  const pageNum = ref(1)
  const pageSize = ref(50)
  const editData = ref({})
  const timeRange = ref([])

  const typeOptions = [
    {
      value: 3,
      label: '实拍讲解'
    },
    {
      value: 4,
      label: '考点视频'
    }
  ]

  const showAddObjectDialog = ref(false)
  const videoDialogVisible = ref(false)
  const previewSrc = ref('')
  const previewTitle = ref('')

  const form = reactive({
    questionName: '',
    carId: '1',
    questionType: '',
    startCreatTime: '',
    endCreateTime: ''
  })

  const tableData = ref([])

  //车型下拉接口
  // const getcarmodellistinfo = async () => {
  //   let obj = {}
  //   const res = await getcarmodellist.getcarmodelId(obj)
  //   if (res.code == 0) {
  //     carList.value = res.data
  //   }
  // }

  const formatDate = (date: string) => {
    return new Date(date)
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      .replace(/\//g, '-')
  }

  const buttonMoreClick = (row: any) => {
    // if (item.key === 'edit') {
    editData.value = JSON.parse(JSON.stringify(row))
    showAddObjectDialog.value = true
    // } else if (item.key === 'delete') {
    //   ElMessageBox.confirm('确定删除该课题吗？', '删除确认', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'error'
    //   }).then(() => {
    //     //执行删除接口
    //     handleDelete(row.id)
    //   })
    // }
  }

  const deleteRole = async (id: string) => {
    ElMessageBox.confirm('确定删除该题库吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      //执行删除接口
      handleDelete(id)
    })
  }

  function getTime(timeArr: string[]) {
    form.startCreatTime = timeArr[0]
    form.endCreateTime = timeArr[1]
    getData()
  }

  function handlePreview(item: Record<string, any>) {
    videoDialogVisible.value = true
    previewSrc.value = item.videoUrl
    previewTitle.value = item.questionName
  }

  async function handleEditStatus(val: any, item: Record<string, any>) {
    try {
      const res = await putquestioncategory.putquestioncategoryId(item.id, {
        isDisplay: val,
        questionName: item.questionName,
        sort: item.sort,
        questionType: item.questionType,
        answer: item.answer,
        categoryId: props.categoryId
      })
      if (res.code === '00000') {
        ElMessage.success('更新成功')
      }
    } catch (e) {
    } finally {
      await getData()
    }
  }

  function handleAdd() {
    showAddObjectDialog.value = true
    editData.value = {
      id: '',
      categoryId: props.categoryId
    }
  }

  function handleCloseDialog(value: boolean) {
    if (value) {
      getData()
      emit('refreshStatc')
    }
    showAddObjectDialog.value = false
  }

  async function handleDelete(id: string) {
    const res = await delquestionlist.delquestionlistId(id)
    if (res.code == '00000') {
      emit('refreshStatc')
      await getData()
    }
  }

  //分页数据处理
  const currentchange = (val: number) => {
    pageNum.value = val
    getData() //请求用户列表接口
  }
  const sizechange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData() //请求用户列表接口
  }

  async function getData() {
    try {
      tableLoading.value = true
      let obj: Record<string, any> = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        categoryId: props.categoryId,
        carId: form.carId,
        type: 1
      }

      for (const key in form) {
        const typedKey = key as keyof typeof form
        if (form[typedKey] !== '') {
          obj[typedKey] = form[typedKey]
        }
      }

      const res = await getupdateList.getupdateId(obj)
      if (res.code === '00000') {
        tableData.value = res.data.list
        pageTotal.value = res.data.total
      }
    } catch (e) {
    } finally {
      tableLoading.value = false
    }
  }

  const selectIds = ref<string[]>([])

  function handleSelectionChange(data: any[]) {
    selectIds.value = data.map((item) => item.id)
  }

  function batchDel() {
    ElMessageBox.confirm('确定批量删除吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(() => {
      let ids = selectIds.value.join(',')
      delImg(ids)
    })
  }

  async function delImg(id: string) {
    const res = await delquestionlist.delquestionlistId(id)
    if (res.code === '00000') {
      emit('refreshStatc')
      await getData()
      ElMessage.success('删除成功')
    }
  }

  async function getStatDataToTypeData() {
    const res = await getStatDataToType({
      carIds: form.carId,
      categoryIds: props.categoryId
    })
    if (res.code === '00000') {
      let data = res.data.filter((item: any) => ![3, 4].includes(item.questionType))
      let result = data.map((item: any) => {
        return `${item.questionTypeName} : ${item.typeCount}`
      })
      staticsQuestionDataInfo.value = result.join(' ; ')
    }
  }

  onMounted(() => {
    // getcarmodellistinfo()
    getData()
    carList.value = props.carStatc?.carStatDataList
    getStatDataToTypeData()
  })
</script>

<style scoped lang="scss">
  .bankcont_title {
    display: flex;
  }

  .bankcont_title_text {
    float: left;
    margin-right: 1rem;
    font-weight: bold;
  }

  .question-content {
    display: flex;

    .left {
      width: 300px;
      margin-right: 20px;
      border-right: 1px solid #ccc;

      .car-model-list {
        width: 300px;
      }

      .car-model-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 10px;
        font-size: 14px;
        cursor: pointer;
        transition: background 0.2s;

        .name {
          display: flex;
          align-items: center;

          .material-icon {
            width: 24px;
            height: 24px;
            margin-right: 6px;
          }
        }
      }

      .car-model-item:hover {
        background-color: #eff8ec;
      }

      .car-model-item.active {
        color: var(--el-color-primary);
        background-color: #eff8ec;
        border-right: 2px solid var(--el-color-primary);
      }

      .car-model-item .count {
        color: #999;
        font-size: 13px;
      }
    }

    .right {
      flex: 1;
      height: 100%;
      padding-top: 10px;
      overflow-x: auto;

      .header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;

        p {
          margin-left: 10px;
          font-size: 12px;
        }
      }
    }
  }
</style>
